package com.gidgabs.modules.base.controller;

import com.gidgabs.common.utils.R;
import com.gidgabs.utils.Base64ToMultipart;
import com.gidgabs.utils.FastDFSClientWrapper;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 文件上传统一接口
 */
@RestController
public class FileUpladController {


    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;


    @PostMapping(value = "/uploadimage")
    public Map fileUpload(MultipartFile upfile) throws IOException {
        try {
            String fileName = upfile.getOriginalFilename();
            String address = fastDFSClientWrapper.uploadFile(upfile);
            Map<String, Object> result = new HashedMap();
            result.put("state", "SUCCESS");
            result.put("url", address);
            result.put("title", fileName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping(value = "/uploadimage1")
    public R fileUpload1(String base64) throws IOException {
        MultipartFile file = Base64ToMultipart.base64ToMultipart(base64);
        String address = fastDFSClientWrapper.uploadFile(file);
        return R.ok().put("address",address);
    }


    @PostMapping(value = "/uploadimage3")
    public R fileUpload3(MultipartFile file) throws IOException {
        String address = fastDFSClientWrapper.uploadFile(file);
        return R.ok().put("address", address);
    }

    @RequestMapping("/uploadimage2")
    public Map fileUpload2(@RequestParam("upImage") File upImage) throws IOException {
        try {
            String fileName = upImage.getName();
            String address = fastDFSClientWrapper.fileUpload2(upImage);
            Map<String, Object> result = new HashedMap();
            result.put("state", "SUCCESS");
            result.put("url", address);
            result.put("title", fileName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @RequestMapping("/delete")
    public R deletFile(String fileAddress) {
        fastDFSClientWrapper.deleteFile(fileAddress);
        return R.ok();
    }
}
